import tools from '@/utils/tools';
import { customPredict } from '@/service/api/predict';
import { chooseMessageFile, textDecoder } from '@/utils/file.js';

import predictStore from '@/store/predict';
import userStore from '@/store/user';
import { createStoreBindings } from '@/miniprogram_npm/mobx-miniprogram-bindings/index';

import { intro, sourceDataColumn, sourceDataDesc } from '@/static/data/predict-intro';

import Message from 'tdesign-miniprogram/message/index';
const messageDefaultConfig = (content) => {
    return {
        context: this,
        offset: [60, 32],
        content: content
    };
};

const timestepValue = [
    { label: '7天', value: 7 },
    { label: '15天', value: 15 },
    { label: '30天', value: 30 }
];

const tableColumns = [
    { title: 'date', key: 'date' },
    { title: 'T_max', key: 'T_max' },
    { title: 'T_min', key: 'T_min' },
    { title: 'P', key: 'P' },
    { title: 'U', key: 'U' },
    { title: 'DD', key: 'DD' },
    { title: 'Ff', key: 'Ff' }
];

let myChart;

Page({
    data: {
        intro, //字段介绍
        sourceDataColumn, // 字段介绍表格表头
        sourceDataDesc, // 字段介绍表格内容
        timestep: 7, // 预测步长
        timestepValue, // 预测步长选择器内容
        popupVisible: false, // 字段介绍弹窗显示
        pickerVisible: false, // 预测步长选择器显示
        tableData: [], // 预测数据表格内容
        tableColumns, // 预测和结果数据表格表头
        resultData: [], // 结果数据表格内容
        ec: {
            lazyLoad: true
        }
    },

    onLoad() {
        this.storeBindings = createStoreBindings(this, {
            store: predictStore,
            fields: ['predictResult', 'tableData'],
            actions: [
                'setTableData',
                'setPredictTempFile',
                'setPredictResult',
                'getPredictTempFile',
                'getPredictResult',
                'resetAll'
            ]
        });
        this.resetAll();
    },

    onUnload() {
        this.storeBindings.destroyStoreBindings();
    },

    // 展示数据格式弹窗
    showDataIntro() {
        this.setData({
            popupVisible: true
        });
    },

    onVisibleChange(e) {
        this.setData({
            popupVisible: e.detail.visible
        });
    },

    chooseTimestep() {
        this.setData({
            pickerVisible: true
        });
    },

    pickerChange(e) {
        this.setData({
            timestep: e.detail.value
        });
        const results = this.getPredictResult(this.data.timestep);
        if (results.length === 0) return;
        this.setData({
            resultData: results
        });
    },

    // 从聊天记录选择预测源文件
    chooseFileFromChat: tools.throttle(async function () {
        try {
            const { tempFile, fileData } = await chooseMessageFile(['json', 'xls', 'xlsx'], 1e6);
            let data = JSON.parse(textDecoder(fileData));
            let keys = Object.keys(data[0]);

            // keys.forEach((key) => {
            //     columns.push({
            //         title: key,
            //         key: key
            //     });
            // });
            this.setTableData(data);
            this.setPredictTempFile(tempFile);
        } catch (err) {
            console.log(err);
            Message.error(messageDefaultConfig(err.message ?? '取消选择'));
        }
    }, 1000),

    // 从本地文件选择预测源文件
    chooseFileFromLocal() {
        // 因为微信小程序限制，需要通过跳转网页调用webApi才能从手机本地存储获取文件
        wx.navigateTo({
            url: '/pages/predict/pages/upload/upload'
        });
    },

    // 根据预测文件获取预测结果
    predictData: tools.throttle(async function () {
        const tempFile = this.getPredictTempFile();
        const userId = userStore.getUserInfo().id;
        if (!tempFile) {
            Message.error(messageDefaultConfig('请上传预测数据'));
            return;
        }
        try {
            const data = {
                userId: userId,
                time_step: 30
            };
            const res = await customPredict(data, tempFile.path);
            this.setPredictResult(res);
            this.setData({
                resultData: res.slice(0, this.data.timestep)
            });
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    }, 1000),

    // 清除预测数据和结果
    clearData() {
        if (!this.getPredictTempFile()) {
            Message.warning(messageDefaultConfig('暂无数据'));
            return;
        }
        wx.showModal({
            title: '警告',
            content: '是否清空当前数据？'
        }).then(() => {
            predictStore.resetAll();
            if (myChart) {
                myChart.clear();
            }
            this.setData({
                resultData: []
            });
        });
    },

    chooseFunction(e) {
        let func = e.currentTarget.dataset.func;
        switch (func) {
            case 'chat':
                this.chooseFileFromChat();
                break;
            case 'file':
                this.chooseFileFromLocal();
                break;
            case 'calc':
                this.predictData();
                break;
            case 'delete':
                this.clearData();
                break;
        }
    }
});
